﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace MangoMes.Write.API.Applications.CraftRoutes
{
    public class CraftRouteListHandler : IRequestHandler<CraftRouteListCommand, PageDTO<CraftRoute>>
    {
        private readonly IBateRepository<CraftRoute> craft;
        public CraftRouteListHandler(IBateRepository<CraftRoute> craft)
        {
            this.craft = craft;
        }
        public async Task<PageDTO<CraftRoute>> Handle(CraftRouteListCommand request, CancellationToken cancellationToken)
        {
            DapperHelper helper = new DapperHelper();
            PageDTO<CraftRoute> dto=new PageDTO<CraftRoute>();
            CraftRoute craftrouten=new CraftRoute();
            
            string conn = helper.MangoMesWrite;
            string str = "select * from craftroute";
            var result = craft.GetAll(str,craftrouten,conn).ToList();
            if (!string.IsNullOrEmpty(request.RouteNo ))
            {
                result = result.Where(x => x.RouteNo == request.RouteNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.RouteName))
            {
                result = result.Where(x => x.RouteName.Contains(request.RouteName)).ToList();
            }
            if (request.IsNo > -1)
            {
                result = result.Where(x => x.IsNo == request.IsNo).ToList();
            }
            dto.TotalCount = result.Count();
            dto.PageCount = (int)Math.Ceiling(result.Count() * 1.0 / request.pageSize);
            result = result.OrderBy(p => p.RouteId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            dto.Data = result;
            return dto;
        }
    }
}
